#include"ObjReader.h"


//split string
void StringSplit(string s, char splitChar, vector<string>& vec)
{
	if (vec.size()) vec.clear();
	int len = s.size();
	int start = 0;

	for(int i=0;i<len;i++){
		if (s[i] == splitChar && i == 0) start++;
		else if (s[i] == splitChar) {
			vec.push_back(s.substr(start, i - start));
			start=i+1;
		}
		else if (i == len - 1) {
			vec.push_back(s.substr(start, i + 1 - start));
		}
	
	}
}



//read .obj file
void ReadObj(string path, Mesh* obj)
{
	ifstream read(path);
	string txt = "";
	if (read) {
		//position buffer
		if (txt[0] == 'v' && txt[1] == ' ') {
			vector<string> vec;
			txt.erase(0, 2);
			StringSplit(txt, ' ', vec);
			Vec4f pos((float)atof(vec[0].c_str()), (float)atof(vec[1].c_str()), (float)atof(vec[2].c_str()));
			obj->positionBuffer.push_back(pos);
		}
		//normal buffer
		else if (txt[0] == 'v' && txt[1] == 'n') {
			vector<string> vec;
			txt.erase(0, 3);
			StringSplit(txt, ' ', vec);
			Vec4f norm((float)atof(vec[0].c_str()), (float)atof(vec[1].c_str()), (float)atof(vec[2].c_str()), 0.0f);
			obj->normalBuffer.push_back(norm);
		}
		//uv buffer
		else if (txt[0] == 'v' && txt[1] == 't') {
			vector<string> vec;
			txt.erase(0, 3);
			StringSplit(txt, ' ', vec);
			Vec2 uv((float)atof(vec[0].c_str()), (float)atof(vec[1].c_str()));
			obj->uvBuffer.push_back(uv);
		}
		//index buffer
		else if (txt[0] == 'f' && txt[1] == ' ') {
			vector<string> vec;
			txt.erase(0, 2);
			StringSplit(txt, ' ', vec);

			for (int i = 0; i < vec.size(); i++) {
				vector<string> vecind;
				StringSplit(vec[i], '/', vecind);
				Vec4i inds(atoi(vecind[0].c_str()), atoi(vecind[1].c_str()), atoi(vecind[2].c_str()));
				obj->indexBuffer.push_back(inds);
			}
		}

	}
	else {
		cout << "File read failed." << endl;
	}

	
}



